<template>
  <div class="membercard-management">
    <ReCommonTable
      ref="tableRef"
      title="充值卡管理"
      :loading="loading"
      :data="tableData"
      :columns="columns"
      :search-fields="searchFields"
      :pagination="pagination"
      @search="handleSearch"
      @refresh="handleRefresh"
      @size-change="handleSizeChange"
      @current-change="handleCurrentPageChange"
      @selection-change="handleSelectionChange"
    >
      <!-- 自定义搜索按钮 -->
      <template #search-buttons>
        <el-button type="primary" @click="handleExport">
          <el-icon>
            <Download />
          </el-icon>
          导出
        </el-button>
        <el-button type="primary" @click="handleNewCard">
          <el-icon>
            <Plus />
          </el-icon>
          开卡
        </el-button>
      </template>

      <!-- 状态列 -->
      <template #status="{ row }">
        <el-tag :type="getStatusType(row.l_status)" size="small">
          {{ getStatusText(row.l_status) }}
        </el-tag>
      </template>

      <!-- 操作列 -->
      <template #action="{ row }">
        <el-button size="small" @click="handleView(row)"> 查看</el-button>
        <el-button
          size="small"
          :disabled="row.l_status !== '1'"
          @click="handleDeduct(row)"
        >
          扣款
        </el-button>
      </template>
    </ReCommonTable>

    <!-- 充值卡详情弹窗 -->
    <el-dialog
      v-model="detailVisible"
      title="充值卡详情"
      width="1200px"
      height="1700px"
      :close-on-click-modal="false"
    >
      <div v-if="currentCard" class="card-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="卡号">
            {{ currentCard.l_cardno }}
          </el-descriptions-item>
          <el-descriptions-item label="折扣卡类型">
            {{ currentCard.c_name }}
          </el-descriptions-item>
          <el-descriptions-item label="会员ID">
            {{ currentCard.l_mid }}
          </el-descriptions-item>
          <el-descriptions-item label="会员姓名">
            {{ currentCard.m_name }}
          </el-descriptions-item>
          <el-descriptions-item label="手机号">
            {{ currentCard.m_mobile }}
          </el-descriptions-item>
          <el-descriptions-item label="卡状态">
            <el-tag :type="getStatusType(currentCard.l_status)" size="small">
              {{ getStatusText(currentCard.l_status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="原始金额">
            ¥{{ currentCard.l_price }}
          </el-descriptions-item>
          <el-descriptions-item label="余额">
            ¥{{ currentCard.l_balance }}
          </el-descriptions-item>
          <el-descriptions-item label="订单号" :span="2">
            {{ currentCard.l_orderno }}
          </el-descriptions-item>
          <el-descriptions-item label="支付流水号" :span="2">
            {{ currentCard.l_paystr || "无" }}
          </el-descriptions-item>
          <el-descriptions-item label="员工">
            {{ currentCard.l_employee || "无" }}
          </el-descriptions-item>
          <el-descriptions-item label="收款方式">
            {{ getPaymentMethodText(currentCard.l_payment_method) }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间" :span="2">
            {{ formatTimestamp(currentCard.l_ctime) }}
          </el-descriptions-item>
          <el-descriptions-item label="付款时间" :span="2">
            {{
              currentCard.l_paytime
                ? formatTimestamp(currentCard.l_paytime)
                : "未付款"
            }}
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">
            {{ currentCard.l_remark || "无" }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 流水记录 -->
        <div style="margin-top: 20px">
          <h3
            style="
              margin-bottom: 16px;
              color: #303133;
              font-size: 16px;
              font-weight: 600;
            "
          >
            流水记录
          </h3>
          <el-table
            v-loading="transactionsLoading"
            :data="transactionsData"
            border
            style="width: 100%"
            empty-text="暂无流水记录"
          >
            <el-table-column
              prop="l_type"
              label="操作类型"
              width="90"
              align="center"
            >
              <template #default="{ row }">
                <el-tag :type="getTransactionType(row.l_type)" size="small">
                  {{ getTransactionText(row.l_type) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              prop="l_pretotal"
              label="变更前金额"
              width="120"
              align="right"
            >
              <template #default="{ row }"> ¥{{ row.l_pretotal }}</template>
            </el-table-column>
            <el-table-column
              prop="l_amount"
              label="变更金额"
              width="90"
              align="right"
            >
              <template #default="{ row }">
                <span style="color: #67c23a">
                  {{ row.l_amount }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
              prop="l_aftertotal"
              label="变更后金额"
              width="120"
              align="right"
            >
              <template #default="{ row }"> ¥{{ row.l_aftertotal }}</template>
            </el-table-column>
            <el-table-column
              prop="l_pname"
              label="关联订单项目"
              width="150"
              show-overflow-tooltip
            >
              <template #default="{ row }">
                {{ row.l_pname || "-" }}
              </template>
            </el-table-column>
            <el-table-column
              prop="l_no"
              label="关联订单号"
              width="180"
              show-overflow-tooltip
            >
              <template #default="{ row }">
                {{ row.l_no || "-" }}
              </template>
            </el-table-column>
            <el-table-column
              prop="l_remark"
              label="备注"
              min-width="200"
              show-overflow-tooltip
            />
            <el-table-column
              prop="l_ctime"
              label="操作时间"
              width="160"
              align="center"
            />
          </el-table>
        </div>
      </div>

      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 新建开卡弹窗 -->
    <el-dialog
      v-model="newCardVisible"
      title="新建开卡"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="newCardFormRef"
        :model="newCardForm"
        :rules="newCardRules"
        label-width="100px"
      >
        <el-form-item label="会员身份" prop="member">
          <el-select
            v-model="newCardForm.member"
            placeholder="请输入手机号搜索会员"
            filterable
            remote
            :remote-method="searchMembers"
            :loading="memberSearchLoading"
            style="width: 100%"
            @change="handleMemberChange"
          >
            <el-option
              v-for="member in memberOptions"
              :key="member.m_id"
              :label="`${member.m_name} (${member.mobile_val})`"
              :value="member.m_id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="折扣卡" prop="cardType">
          <el-select
            v-model="newCardForm.cardType"
            placeholder="请选择折扣卡"
            style="width: 100%"
          >
            <el-option
              v-for="card in discountCardOptions"
              :key="card.c_id"
              :label="`${card.c_name}`"
              :value="card.c_id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="充值金额" prop="amount">
          <el-input-number
            v-model="newCardForm.amount"
            :min="0"
            :precision="2"
            style="width: 100%"
            placeholder="请输入充值金额"
          />
          <div style="font-size: 12px; color: #909399; margin-top: 4px">
            充值金额，默认为0，表示读取卡上的金额
          </div>
        </el-form-item>
        <el-form-item label="充值来源" prop="paymentMethod">
          <el-select
            v-model="newCardForm.paymentMethod"
            placeholder="请选择充值来源"
            style="width: 100%"
          >
            <el-option
              v-for="(label, value) in paymentMethodOptions"
              :key="value"
              :label="label"
              :value="value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="员工" prop="employee">
          <el-select
            v-model="newCardForm.employee"
            placeholder="请选择员工"
            filterable
            style="width: 100%"
            @change="handleEmployeeChange"
          >
            <el-option
              v-for="employee in employeeOptions"
              :key="employee.t_id"
              :label="`${employee.t_name} (${employee.t_mobile})`"
              :value="employee.t_id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="newCardForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="newCardVisible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="createLoading"
          @click="handleCreateCard"
        >
          确认开卡
        </el-button>
      </template>
    </el-dialog>

    <!-- 扣款弹窗 -->
    <el-dialog
      v-model="deductVisible"
      title="充值卡扣款"
      width="500px"
      :close-on-click-modal="false"
    >
      <div v-if="currentCard" class="deduct-info">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="卡号">
            {{ currentCard.l_cardno }}
          </el-descriptions-item>
          <el-descriptions-item label="会员姓名">
            {{ currentCard.m_name }}
          </el-descriptions-item>
          <el-descriptions-item label="当前余额">
            ¥{{ currentCard.l_balance }}
          </el-descriptions-item>
        </el-descriptions>

        <el-form
          ref="deductFormRef"
          :model="deductForm"
          :rules="deductRules"
          label-width="100px"
          style="margin-top: 20px"
        >
          <el-form-item label="关联订单" prop="orderId">
            <el-select
              v-model="deductForm.orderId"
              placeholder="请选择订单（可选）"
              style="width: 100%"
              clearable
              filterable
              @change="handleOrderChange"
            >
              <el-option
                v-for="(order, index) in unpaidOrderOptions"
                :key="order.l_id"
                :label="`${order.l_pname} - ${order.l_mname} - ¥${order.l_price}`"
                :value="order.l_id"
              >
                <div style="display: flex; justify-content: space-between">
                  <span>{{ order.l_pname }} - {{ order.l_mname }}</span>
                  <span style="color: #8492a6; font-size: 13px"
                    >¥{{ order.l_price }}</span
                  >
                </div>
                <div style="font-size: 12px; color: #909399; margin-top: 2px">
                  {{ formatTimestamp(order.l_yytime) }}
                </div>
              </el-option>
            </el-select>
            <div style="font-size: 12px; color: #909399; margin-top: 4px">
              选择订单后可关联扣款记录，不选择则为普通扣款
            </div>
          </el-form-item>

          <el-form-item label="扣款金额" prop="amount">
            <el-input-number
              v-model="deductForm.amount"
              :max="parseFloat(currentCard.l_balance)"
              :precision="2"
              style="width: 100%"
              placeholder="请输入扣款金额"
            />
            <div style="font-size: 12px; color: #909399; margin-top: 4px">
              如果扣款金额为负数，则是为卡充值
            </div>
          </el-form-item>

          <el-form-item label="扣款备注" prop="remark">
            <el-input
              v-model="deductForm.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入扣款原因或备注（必填）"
            />
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <el-button @click="deductVisible = false">取消</el-button>
        <el-button
          type="danger"
          :loading="deductLoading"
          @click="handleConfirmDeduct"
        >
          确认扣款
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Download } from "@element-plus/icons-vue";
import { ReCommonTable } from "@/components/ReCommonTable";
import type {
  SearchField,
  TableColumn
} from "@/components/ReCommonTable/src/index.vue";
import {
  getMemberCardList,
  getPaymentMethods,
  getDiscountCards,
  getMemberInfo,
  createNewCard,
  deductMemberCard,
  getMemberCardTransactions,
  exportMemberCardData,
  type MemberCard,
  type MemberCardSearchParams,
  type MemberInfo,
  type DiscountCard,
  type PaymentMethod,
  type NewCardParams,
  type MemberCardTransaction
} from "@/api/membercard";
import {
  getEmployeeList,
  type Employee,
  type EmployeeSearchParams
} from "@/api/employee";
import {
  getOrderList,
  getUnpaidOrderList,
  getOrderAmount,
  type UnpaidOrder,
  type OrderAmount
} from "@/api/order";

defineOptions({
  name: "MemberCardManagement"
});

// 响应式数据
const loading = ref(false);
const detailVisible = ref(false);
const newCardVisible = ref(false);
const deductVisible = ref(false);
const createLoading = ref(false);
const deductLoading = ref(false);
const memberSearchLoading = ref(false);
const transactionsLoading = ref(false); // 流水加载状态
const tableRef = ref();
const newCardFormRef = ref();
const deductFormRef = ref();
const selectedRows = ref([]);
const currentCard = ref<MemberCard | null>(null);
const transactionsData = ref<MemberCardTransaction[]>([]); // 流水数据

// 搜索表单
const searchForm = ref<MemberCardSearchParams>({});

// 表格数据
const tableData = ref([]);

// 分页配置
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0,
  pageSizes: [10, 20, 50, 100],
  layout: "total, sizes, prev, pager, next, jumper",
  background: true,
  disabled: false,
  paginationSize: "default"
});

// 选项数据
const memberOptions = ref<MemberInfo[]>([]);
const discountCardOptions = ref<DiscountCard[]>([]);
const paymentMethodOptions = ref<PaymentMethod>({});
const employeeOptions = ref<Employee[]>([]);
const unpaidOrderOptions = ref<UnpaidOrder[]>([]);

// 新建开卡表单
const newCardForm = ref({
  member: "",
  cardType: "",
  paymentMethod: "",
  employee: "",
  amount: 0,
  remark: ""
});

// 扣款表单
const deductForm = ref({
  amount: 0,
  remark: "",
  oid: "",
  orderId: "" // 订单ID（可选）
});

// 搜索字段配置
const searchFields: SearchField[] = [
  {
    prop: "keys",
    label: "手机号末尾",
    type: "input",
    placeholder: "请输入手机号末尾数字搜索"
  }
];

// 表格列配置
const columns: TableColumn[] = [
  {
    prop: "l_cardno",
    label: "卡号",
    width: 180,
    fixed: "left",
    showOverflowTooltip: true
  },
  {
    prop: "l_mid",
    label: "会员ID",
    width: 120
  },
  {
    prop: "m_name",
    label: "会员姓名",
    showOverflowTooltip: true
  },
  {
    prop: "m_mobile",
    label: "手机号"
  },
  {
    prop: "c_name",
    label: "几折卡"
  },
  {
    prop: "l_price",
    label: "原始金额",
    width: 120,
    formatter: row => `¥${row.l_price}`
  },
  {
    prop: "l_balance",
    label: "余额",
    width: 120,
    formatter: row => `¥${row.l_balance}`
  },
  {
    prop: "l_status",
    label: "状态",
    width: 120,
    slot: "status"
  },
  {
    label: "操作",
    fixed: "right",
    width: 140,
    slot: "action"
  }
];

// 表单验证规则
const newCardRules = {
  member: [{ required: true, message: "请选择会员", trigger: "change" }],
  cardType: [{ required: true, message: "请选择折扣卡", trigger: "change" }],
  paymentMethod: [
    { required: true, message: "请选择充值来源", trigger: "change" }
  ],
  employee: [{ required: true, message: "请选择员工", trigger: "change" }],
  remark: [{ required: true, message: "请输入备注", trigger: "blur" }]
};

const deductRules = {
  amount: [{ required: true, message: "请输入扣款金额", trigger: "blur" }],
  remark: [{ required: true, message: "请输入扣款备注", trigger: "blur" }]
};

// 工具函数
const getStatusType = (status: string) => {
  const statusMap = {
    "0": "warning", // 未支付
    "1": "success", // 支付完成
    "2": "info", // 钱已用完
    "3": "danger", // 卡作废
    "4": "danger" // 支付失败
  };
  return statusMap[status] || "info";
};

const getStatusText = (status: string) => {
  const statusMap = {
    "0": "未支付",
    "1": "支付完成",
    "2": "钱已用完",
    "3": "卡作废",
    "4": "支付失败"
  };
  return statusMap[status] || "未知";
};

const getPaymentMethodText = (method: string) => {
  return paymentMethodOptions.value[method] || "未知";
};

const formatTimestamp = (timestamp: string) => {
  if (!timestamp || timestamp === "0") return "";
  const date = new Date(parseInt(timestamp) * 1000);
  return date.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit"
  });
};

// 事件处理
const handleSearch = (searchParams: any) => {
  console.log("搜索参数:", searchParams);
  searchForm.value = searchParams;
  pagination.current = 1;
  loadData();
};

const handleRefresh = () => {
  loadData();
};

const handleSizeChange = (size: number) => {
  pagination.size = size;
  pagination.current = 1;
  loadData();
};

const handleCurrentPageChange = (current: number) => {
  pagination.current = current;
  loadData();
};

const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection;
};

const handleView = async (row: MemberCard) => {
  currentCard.value = row;
  detailVisible.value = true;
  // 自动加载流水数据
  await loadTransactions(parseInt(row.l_id));
};

const handleNewCard = () => {
  newCardForm.value = {
    member: "",
    cardType: "",
    paymentMethod: "",
    employee: "",
    amount: 0,
    remark: ""
  };
  newCardVisible.value = true;
  loadOptions();
  loadEmployees(); // 加载员工列表
};

const handleDeduct = async (row: MemberCard) => {
  if (row.l_status !== "1") {
    ElMessage.warning("只有支付完成的卡片才能扣款");
    return;
  }
  currentCard.value = row;
  deductForm.value = {
    amount: 0,
    remark: "",
    orderId: ""
  };

  // 加载该会员的未支付订单列表
  try {
    const response = await getUnpaidOrderList({ mid: parseInt(row.l_mid) });
    if (response.code === 1) {
      unpaidOrderOptions.value = response.data;
    } else {
      console.warn("获取未支付订单失败:", response.msg);
      unpaidOrderOptions.value = [];
    }
  } catch (error) {
    console.error("获取未支付订单失败:", error);
    unpaidOrderOptions.value = [];
  }

  deductVisible.value = true;
};

// 处理订单选择变化
const handleOrderChange = async (l_id: string) => {
  console.log(l_id);
  try {
    deductForm.value.oid = l_id;
    // 调用获取订单应支付金额接口
    const response = await getOrderAmount({
      cid: currentCard.value.l_id, // 使用充值卡ID作为折扣卡ID
      oid: l_id // 使用订单ID
    });

    if (response.code === 1 && response.data) {
      // 将接口返回的打折后价格赋值给扣款金额
      deductForm.value.amount = parseFloat(response.data.total);
      ElMessage.success(`已自动计算扣款金额：¥${response.data.total}`);
    } else {
      // 如果接口失败，使用订单原价格
      ElMessage.warning("获取订单折扣金额失败");
    }
  } catch (e) {
    ElMessage.warning("获取订单失败");
  }
};

// 搜索会员
const searchMembers = async (query: string) => {
  if (!query) {
    memberOptions.value = [];
    return;
  }

  memberSearchLoading.value = true;
  try {
    const response = await getMemberInfo(query);
    if (response.code === 1) {
      memberOptions.value = response.data;
    }
  } catch (error) {
    console.error("搜索会员失败:", error);
  } finally {
    memberSearchLoading.value = false;
  }
};

// 会员选择变化
const handleMemberChange = (memberId: string) => {
  const selectedMember = memberOptions.value.find(m => m.m_id === memberId);
  if (selectedMember) {
    console.log("选中会员:", selectedMember);
  }
};

// 加载员工列表
const loadEmployees = async () => {
  try {
    const response = await getEmployeeList({
      status: "1", // 只加载在职员工
      num: "100", // 加载更多员工
      page: "1"
    });
    if (response.code === 1) {
      employeeOptions.value = response.data.list;
    }
  } catch (error) {
    console.error("加载员工列表失败:", error);
  }
};

// 员工选择变化
const handleEmployeeChange = (employeeId: string) => {
  const selectedEmployee = employeeOptions.value.find(
    e => e.t_id === employeeId
  );
  if (selectedEmployee) {
    console.log("选中员工:", selectedEmployee);
  }
};

// 创建新卡
const handleCreateCard = async () => {
  if (!newCardFormRef.value) return;

  try {
    await newCardFormRef.value.validate();

    createLoading.value = true;

    const params: NewCardParams = {
      mid: parseInt(newCardForm.value.member),
      cid: parseInt(newCardForm.value.cardType),
      payment_method: parseInt(newCardForm.value.paymentMethod),
      employee: newCardForm.value.employee, // 现在这是员工ID
      amount: newCardForm.value.amount,
      remark: newCardForm.value.remark
    };

    const response = await createNewCard(params);

    if (response.code === 1) {
      ElMessage.success("开卡成功");
      newCardVisible.value = false;
      loadData();
    } else {
      ElMessage.error(response.msg || "开卡失败");
    }
  } catch (error) {
    console.error("开卡失败:", error);
    ElMessage.error("开卡失败");
  } finally {
    createLoading.value = false;
  }
};

// 确认扣款
const handleConfirmDeduct = async () => {
  if (!deductFormRef.value || !currentCard.value) return;

  try {
    await deductFormRef.value.validate();

    // 构建确认信息
    let confirmMessage = `确认从卡号 ${currentCard.value.l_cardno} 扣款 ¥${deductForm.value.amount} 吗？`;
    if (deductForm.value.orderId !== "") {
      const selectedOrder = unpaidOrderOptions.value.find(
        order => order.l_yytime === deductForm.value.orderId
      );
      if (selectedOrder) {
        confirmMessage += `\n关联订单：${selectedOrder.l_pname} - ${selectedOrder.l_mname}`;
        confirmMessage += `\n预约时间：${formatTimestamp(selectedOrder.l_yytime)}`;
      }
    }

    await ElMessageBox.confirm(confirmMessage, "确认扣款", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning"
    });

    deductLoading.value = true;
    console.log("选中订单:", deductForm.value);
    // 准备扣款参数
    const deductParams: any = {
      oid: deductForm.value.oid, // 将在下面根据选中的订单设置
      cardId: currentCard.value.l_id,
      amount: deductForm.value.amount,
      remark: deductForm.value.remark
    };

    // 如果选择了订单，添加订单信息
    if (deductForm.value.orderId !== "") {
      const selectedOrder = unpaidOrderOptions.value.find(
        order => order.l_yytime === deductForm.value.orderId
      );
      if (selectedOrder) {
        deductParams.orderTime = selectedOrder.l_yytime;
        // 在备注中添加订单信息，便于后续查看
        // deductParams.remark += ` [关联订单: ${selectedOrder.l_pname} - ${formatTimestamp(selectedOrder.l_yytime)}]`;
      }
    }

    const response = await deductMemberCard(deductParams);

    if (response.code === 1) {
      ElMessage.success("扣款成功");
      deductVisible.value = false;
      loadData();
    } else {
      ElMessage.error(response.msg || "扣款失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("扣款失败:", error);
      ElMessage.error("扣款失败");
    }
  } finally {
    deductLoading.value = false;
  }
};

// 加载选项数据
const loadOptions = async () => {
  try {
    // 加载折扣卡列表
    const discountResponse = await getDiscountCards();
    if (discountResponse.code === 1) {
      discountCardOptions.value = discountResponse.data;
    }

    // 加载收款方式
    const paymentResponse = await getPaymentMethods();
    if (paymentResponse.code === 1) {
      paymentMethodOptions.value = paymentResponse.data;
    }
  } catch (error) {
    console.error("加载选项数据失败:", error);
  }
};

// 导出数据
const handleExport = async () => {
  try {
    loading.value = true;

    // 使用当前搜索条件作为导出参数
    const exportParams = {
      keys: searchForm.value.keys || ""
    };

    const response = await exportMemberCardData(exportParams);

    // 创建下载链接
    const blob = new Blob([response.data], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;

    // 从响应头获取文件名
    let filename = "充值卡数据.xlsx"; // 默认文件名
    const contentDisposition = response.headers?.["content-disposition"];
    if (contentDisposition) {
      const filenameMatch = contentDisposition.match(
        /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/
      );
      if (filenameMatch && filenameMatch[1]) {
        filename = filenameMatch[1].replace(/['"]/g, "");
        // 处理编码问题
        try {
          filename = decodeURIComponent(filename);
        } catch (e) {
          // 如果解码失败，使用原始文件名
          console.warn("文件名解码失败:", e);
        }
      }
    }

    // 如果没有从响应头获取到文件名，使用时间戳生成
    if (filename === "充值卡数据.xlsx") {
      const now = new Date();
      const timestamp = now.toISOString().replace(/[:.]/g, "").slice(0, -5); // 格式：20250805T1534
      filename = `充值卡数据_${timestamp}.xlsx`;
    }

    link.download = filename;

    // 触发下载
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);

    ElMessage.success("导出成功");
  } catch (error) {
    console.error("导出失败:", error);
    ElMessage.error("导出失败，请稍后重试");
  } finally {
    loading.value = false;
  }
};

// 加载数据
const loadData = async () => {
  loading.value = true;

  try {
    const params: MemberCardSearchParams = {
      num: pagination.size,
      page: pagination.current,
      ...searchForm.value
    };

    // 尝试调用API
    try {
      const response = await getMemberCardList(params);

      if (response.code === 1) {
        tableData.value = response.data.list;
        pagination.total = Number(response.data.total);
        return;
      } else {
        ElMessage.error(response.msg || "数据加载失败");
      }
    } catch (apiError) {
      console.log("API调用失败，使用模拟数据");
    }
  } catch (error) {
    console.error("数据加载错误:", error);
    ElMessage.error("数据加载失败");
  } finally {
    loading.value = false;
  }
};

// 加载流水数据
const loadTransactions = async (cardId: number) => {
  transactionsLoading.value = true;
  try {
    const response = await getMemberCardTransactions({ cid: cardId });
    if (response.code === 1) {
      // 处理无数据的情况，当list为0时设为空数组
      const listData = Array.isArray(response.data.list)
        ? response.data.list
        : [];
      transactionsData.value = listData.map(item => ({
        ...item,
        l_ctime: formatTimestamp(item.l_ctime)
      }));
    } else {
      ElMessage.error(response.msg || "流水数据加载失败");
      transactionsData.value = [];
    }
  } catch (error) {
    console.error("加载流水数据失败:", error);
    ElMessage.error("流水数据加载失败");
    transactionsData.value = [];
  } finally {
    transactionsLoading.value = false;
  }
};

// 获取交易类型标签样式
const getTransactionType = (type: string) => {
  const typeMap = {
    "1": "primary", // 前端操作
    "2": "warning" // 后端操作
  };
  return typeMap[type] || "info";
};

// 获取交易类型文本
const getTransactionText = (type: string) => {
  const typeMap = {
    "1": "前端操作",
    "2": "后端操作"
  };
  return typeMap[type] || "未知";
};

// 获取交易金额颜色
const getTransactionAmountColor = (amount: string) => {
  return parseFloat(amount) > 0 ? "#67C23A" : "#F56C6C";
};

// 生命周期
onMounted(() => {
  loadData();
  loadOptions();
});
</script>

<style scoped>
.membercard-management {
  height: 100%;
  background: #f5f7fa;
}

.card-detail {
  max-height: 500px;
  overflow-y: auto;
}

.deduct-info {
  margin-bottom: 20px;
}

:deep(.el-descriptions) {
  --el-descriptions-item-bordered-label-background: #fafafa;
}

.dark :deep(.el-descriptions) {
  --el-descriptions-item-bordered-label-background: #262727;
}

:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-select) {
  width: 100%;
}
</style>
